import time
import json
import uuid
import sqlite3

from fastapi import APIRouter, Depends, HTTPException, Response, Query
from models import DialogueHistoryTag, DialogueHistory, Dialogue, CreateDialogueRequest
from typing import List, Optional

from routes.auth import vali_token

router = APIRouter()


# # 获取所有对话历史tags
# @router.get("/dialogue_history/", response_model=List[DialogueHistoryTag])
# async def get_dialogue_history_tags(access_key_id: int = Depends(vali_token)):

#     conn = sqlite3.connect('database.db')
#     cursor = conn.cursor()
#     cursor.execute(
#         'SELECT uuid, last_modified_time, title '
#         'FROM dialogue_history '
#         'WHERE access_key_id = ? '
#         'ORDER BY last_modified_time DESC',
#         (access_key_id,)
#     )
#     rows = cursor.fetchall()
#     conn.close()
    
#     return [DialogueHistoryTag(uuid=row[0], last_modified_time=row[1], title=row[2] ) for row in rows]

def get_non_conflicting_last_modified_time(cursor, access_key_id):
    non_conflicting_last_modified_time = None
    last_modified_time = int(time.time())
    while(not non_conflicting_last_modified_time):
        cursor.execute(
            """
            SELECT *
            FROM dialogue_history
            WHERE access_key_id = ?
            AND last_modified_time = ?
            """,
            (access_key_id, last_modified_time)
        )
        rows = cursor.fetchall()
        if not rows:
            non_conflicting_last_modified_time = last_modified_time
        else:
            last_modified_time += 1
    return non_conflicting_last_modified_time


@router.get(
    "/dialogue_history/",
    response_model=List[DialogueHistoryTag],
    summary="滚动加载对话历史标签"
)
async def get_dialogue_history_tags(
    access_key_id: int = Depends(vali_token),
    last_modified_time: int = None,
    page_size: int = Query(25, gt=0, le=100, description="一次拉取条数")
):
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()

    # --------- ① 若未传 last_modified_time：拉取最新 page_size 条 ---------
    if last_modified_time is None:
        cursor.execute(
            """
            SELECT uuid, last_modified_time, title
            FROM dialogue_history
            WHERE access_key_id = ?
            ORDER BY last_modified_time DESC
            LIMIT ?
            """,
            (access_key_id, page_size)
        )
        rows = cursor.fetchall()
        conn.close()
        return [
            DialogueHistoryTag(
                uuid=row[0], last_modified_time=row[1], title=row[2]
            ) for row in rows
        ]
    # elif last_uuid is None:
    #     raise HTTPException(status_code=400, detail="When the last_modified_time parameter is passed, the last_uuid parameter should also be passed")

    # --------- ② 取更早的 page_size 条 ---------
    cursor.execute(
        """
        SELECT uuid, last_modified_time, title
        FROM dialogue_history
        WHERE access_key_id = ?
        AND last_modified_time < ?
        ORDER BY last_modified_time DESC
        LIMIT ?
        """,
        (access_key_id, last_modified_time, page_size)
    )
    rows = cursor.fetchall()
    conn.close()

    return [
        DialogueHistoryTag(
            uuid=r[0], last_modified_time=r[1], title=r[2]
        ) for r in rows
    ]


# 根据uuid获取对话历史tag
@router.get("/dialogue_history/{dialogue_uuid}", response_model=DialogueHistoryTag)
async def get_dialogue_history_tags(dialogue_uuid: str, access_key_id: int = Depends(vali_token)):

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute(
        'SELECT uuid, last_modified_time, title FROM dialogue_history WHERE access_key_id = ? AND uuid = ? ',
        (access_key_id, dialogue_uuid)
    )
    row = cursor.fetchone()
    conn.close()
    # return rows
    return DialogueHistoryTag(uuid=row[0], last_modified_time=row[1], title=row[2])

# 根据UUID获取对话
@router.get("/dialogue/{dialogue_uuid}", response_model=Dialogue)
async def get_dialogue(dialogue_uuid: str, access_key_id: int = Depends(vali_token)):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute(
        'SELECT current_model, dialogue_content_json FROM dialogue_history WHERE access_key_id = ? AND uuid = ?',
        (access_key_id, dialogue_uuid)
    )
    row = cursor.fetchone()
    conn.close()
    # print(row)

    if row is None:
        raise HTTPException(status_code=404, detail="Item not found")
    if row[1]:
        return Dialogue(current_model = row[0], dialogue_content_json=json.loads(row[1]))
    else:
        return Dialogue(current_model = row[0], dialogue_content_json=[])

# 创建对话
@router.post("/dialogue/", response_model=DialogueHistory)
def create_dialogue(request: CreateDialogueRequest, access_key_id: int = Depends(vali_token)):
    # access_key_id = vali_access_key(token)
    created_time = int(time.time())
    # last_modified_time = created_time
    random_uuid = str(uuid.uuid4())
    # print(random_uuid)
    # print(request)

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    last_modified_time = get_non_conflicting_last_modified_time(cursor, access_key_id)
    # print(type(random_uuid), type(access_key_id), type(created_time), type(last_modified_time), type(request.dialogue_content_json))
    cursor.execute(
        'INSERT INTO '
        'dialogue_history (uuid, access_key_id, created_time, last_modified_time, current_model, dialogue_content_json) '
        'VALUES (?, ?, ?, ?, ?, ?)',
        (random_uuid, access_key_id, created_time, last_modified_time, request.current_model, json.dumps(request.dialogue_content_json))
    )
    conn.commit()

    # 查询刚插入的行数据
    cursor.execute(
        'SELECT uuid, created_time, last_modified_time, title, current_model, topic_id, dialogue_content_json '
        'FROM dialogue_history '
        'WHERE uuid = ? ' ,
        (random_uuid,)
    )
    row = cursor.fetchone()
    conn.close()

    return DialogueHistory(
        uuid=row[0], created_time=row[1], last_modified_time=row[2],
        title=row[3], current_model=row[4], topic_id=row[5], dialogue_content_json=json.loads(row[6]))


# 更新详细对话
@router.put("/dialogue/{dialogue_uuid}", response_model=None)
def put_dialogue_json(dialogue_uuid: str, request: Dialogue, access_key_id: int = Depends(vali_token)):
    # print(request)

    # last_modified_time = int(time.time())

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    last_modified_time = get_non_conflicting_last_modified_time(cursor, access_key_id)
    cursor.execute(
        'UPDATE dialogue_history SET current_model=? , dialogue_content_json = ?, last_modified_time = ? WHERE access_key_id = ? AND uuid = ?',
        (request.current_model, json.dumps(request.dialogue_content_json), last_modified_time, access_key_id, dialogue_uuid)
    )
    conn.commit()
    conn.close()

    if cursor.rowcount == 0:
        raise HTTPException(status_code=404, detail="Item not found")


    # return DialogueResponse(dialogue_json=request.dialogue_json)

# 删除对话
@router.delete("/dialogue/{dialogue_uuid}", response_model=None)
def delete_dialogue(dialogue_uuid: str, access_key_id: int = Depends(vali_token)):

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute(
        'DELETE FROM dialogue_history WHERE access_key_id = ? AND uuid = ?',
        (access_key_id, dialogue_uuid)
    )
    conn.commit()
    conn.close()

    if cursor.rowcount == 0:
        raise HTTPException(status_code=404, detail="Item not found")

    # return {"detail": "Dialogue deleted successfully"}

# 更新标题名
@router.put("/dialogue_history/title/")
def update_dialogue_history_title(request: DialogueHistoryTag, access_key_id: int = Depends(vali_token)):
    # print(request)

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute(
        'UPDATE dialogue_history SET title=? WHERE access_key_id = ? AND uuid = ?',
        (request.title, access_key_id, request.uuid)
    )
    conn.commit()
    conn.close()

    if cursor.rowcount == 0:
        raise HTTPException(status_code=404, detail="Item not found")

